package com.colin.mvp.download.model;

import com.colin.constant.Constants;
import com.colin.http.HttpServiceManager;
import com.colin.utils.FileUtil;
import com.colin.utils.LogUtil;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

/**
 * Created by colin on 2018/1/20.
 */

public class MainModel1 implements MainModel {
	@Override
	public void downloadFile(@NotNull String url) {

		HttpServiceManager.getInstance()
			.getHttpService()
			.downloadFile(url)
			.subscribeOn(Schedulers.newThread())
			.observeOn(Schedulers.io())
			.subscribe(new Consumer<ResponseBody>() {
				@Override
				public void accept(ResponseBody responseBody) throws Exception {
//					LogUtil.e("开始下载。。。");
					long contentLen = responseBody.contentLength();
					MediaType type = responseBody.contentType();
					InputStream bis = responseBody.byteStream();
					int len = 0;
					long writeLen = 0;
					byte[] buf = new byte[2048];
					FileOutputStream fos = new FileOutputStream(new File(Constants.apkPath));
					while (-1!=(len = bis.read(buf))){
						writeLen += len;
						fos.write(buf,0,len);
					}
					fos.close();
					bis.close();
//					LogUtil.e("contentLen = "+contentLen);
//					LogUtil.e("writeLen = "+writeLen);
//					LogUtil.e("Constants.apkPath = "+Constants.apkPath);
					if (contentLen == writeLen){
						LogUtil.e("下载完成！");
					}
				}
			});
	}



	@Override
	public void uploadFiles(@NotNull File... files) {
		MultipartBody.Builder builder =new MultipartBody.Builder();
		builder.setType(MultipartBody.FORM);
		for (File file : files) {
			builder.addFormDataPart("file",file.getName(), RequestBody.create(MediaType.parse(FileUtil.getMIMEType(file)),file));
		}
		HttpServiceManager.getInstance()
			.getHttpService()
			.uploadFiles1(builder.build())
			.subscribeOn(Schedulers.newThread())
			.observeOn(Schedulers.io())
			.subscribe(new Consumer<ResponseBody>() {
				@Override
				public void accept(ResponseBody responseBody) throws Exception {
					String response = responseBody.string();
					LogUtil.e("upload:" + response);
				}
			}, new Consumer<Throwable>() {
				@Override
				public void accept(Throwable throwable) throws Exception {
					LogUtil.e("upload:"+throwable.getMessage());
				}
			});
	}
}
